package cn.knight.system.service.impl;

import cn.knight.basic.service.impl.BaseServiceImpl;
import cn.knight.org.domain.Department;
import cn.knight.system.domain.Menu;
import cn.knight.system.mapper.MenuMapper;
import cn.knight.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author winnie
 * @since 2022-07-11
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private  MenuMapper menuMapper;

    @Override
    public List<Menu> tree() {
        //获取所有数据
        List<Menu> menus = menuMapper.loadAll();
        //创建一个装最终结果的集合
        List<Menu> menuList =  new ArrayList<>();
        //为了解决时间复杂度，转为map
        Map<Long, Menu> menuMap = new HashMap<>();
        for(Menu menu : menus){
            menuMap.put(menu.getId(),menu);
        }
        //先把一级数据找出来
        for (Menu menu : menus){
            if (menu.getParentId() == null){
                menuList.add(menu);
            }else {
                Menu menuTmp = menuMap.get(menu.getParentId());
                if (menuTmp != null){
                    menuTmp.getChildren().add(menu);
                }
            }
        }
        return menuList;
    }


}
